import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:new_yuqib_app/yqbConfig/custom_font_style.dart';
import 'package:new_yuqib_app/yqbConfig/tencent_im_utils.dart';
import 'package:new_yuqib_app/yqbConfig/yqb_app.dart';
import 'package:new_yuqib_app/yqbNetwork/api_metholds.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/separate_models/tui_chat_separate_view_model.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_chat_global_model.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:url_launcher/url_launcher.dart';

///聊天界面
class TencentChatPage extends StatefulWidget {
  final String serviceId;
  final String phone;

  const TencentChatPage({
    super.key,
    required this.serviceId,
    required this.phone,
  });

  @override
  State<TencentChatPage> createState() => _TencentChatPageState();
}

class _TencentChatPageState extends State<TencentChatPage> {
  @override
  void initState() {
    super.initState();
    ApiMethods.enterChat(widget.serviceId);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        TIMUIKitChat(
          conversationID: widget.serviceId,
          conversationType: ConvType.c2c,
          controller: TencentImUtils.messageController,
          userAvatarBuilder: (context,v2TimMessage){
            if(v2TimMessage.nickName!.isPhoneNumber){
              return Image.asset("images/default_avatar.png",width: 46);
            }else{
              return Image.asset("images/services_avatar.png");
            }
          },
          config: const TIMUIKitChatConfig(
            // 仅供演示，非全部配置项，实际使用中，可只传和默认项不同的参数，无需传入所有开关
            isAllowClickAvatar: true,
            isUseDefaultEmoji: true,
            isAllowLongPressMessage: true,
            isShowReadingStatus: true,
            isShowGroupReadingStatus: true,
            notificationTitle: "",
            isUseMessageReaction: true,
          ),
          textFieldBuilder: (context) {
            return TIMUIKitInputTextField(
              conversationID: widget.serviceId,
              conversationType: ConvType.c2c,
              model: TUIChatSeparateViewModel(),
              hintText: "描述您的问题",
              isUseDefaultEmoji: true,
              showMorePanel: false,
              showSendAudio: false,
              showSendEmoji: false,
              morePanelConfig: MorePanelConfig(
                showCameraAction: false,
              ),
              currentConversation: V2TimConversation(conversationID: widget.serviceId, type: 1),
            );
          },
          appBarConfig: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(onPressed: Get.back, icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black)),
            title: const Text("专属客服"),
            centerTitle: true,
            titleTextStyle: CustomFontStyle.defaultStyle(size: 18),
          ),
          conversation: V2TimConversation(conversationID: widget.serviceId, type: 1),
          messageItemBuilder: MessageItemBuilder(customMessageItemBuilder: (message, isShowJump, clearJump) {
            if (message.customElem != null) {
              return GestureDetector(
                onTap: () {
                Fluwx().open(target: MiniProgram(username: YqbApp.miniProgramID, path: YqbApp.miniProgramPath(id: YqbApp.getServiceData()!.id)));
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: Colors.grey.shade300, width: 0.5),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.asset(
                            'images/wechat.png',
                            width: 35,
                          ),
                          const SizedBox(width: 15),
                          const Text(
                            "点击添加\n法务老师微信\n",
                            style: TextStyle(
                              fontSize: 16,
                              letterSpacing: 1.2,
                            ),
                          )
                        ],
                      ),
                      Container(
                        width: double.maxFinite,
                        height: 1,
                        color: Colors.grey.shade200,
                      )
                    ],
                  ),
                ),
              );
            }else{
              return null;
            }
          }),
        ),
        Positioned(
          bottom: 70+MediaQuery.of(context).viewInsets.bottom,
          left: 16,
          child: Row(
            children: [
              GestureDetector(onTap: () {
                Get.dialog(
                  Dialog(
                    backgroundColor: Colors.white,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const SizedBox(height: 12),
                        Text(
                          "权限申请说明",
                          style: CustomFontStyle.titleStyle(fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 16),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 12),
                          child: Text(
                            "为了实现快捷拨号功能，需要您确定后方能使用",
                            style: CustomFontStyle.defaultStyle(size: 16),
                          ),
                        ),
                        const SizedBox(height: 16),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            ElevatedButton(
                              onPressed: Get.back,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: const Color(0XFFCFCFCF),
                                padding: const EdgeInsets.symmetric(horizontal: 24),
                              ),
                              child: Text(
                                "取消",
                                style: CustomFontStyle.defaultStyle(
                                  size: 16,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                            ElevatedButton(
                              onPressed: () {
                                Get.back();
                                launch('tel:${widget.phone}');
                              },
                              style: ElevatedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(horizontal: 24),
                              ),
                              child: Text(
                                "确定",
                                style: CustomFontStyle.defaultStyle(size: 16, color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),
                      ],
                    ),
                  ),
                );
              }, child: Image.asset("images/chat_phone.png", width: 125)),
              const SizedBox(width: 12),
              Visibility(
                visible: YqbApp.jumpXcx == 1,
                child: GestureDetector(onTap: () {
                  Fluwx().open(target: MiniProgram(username: YqbApp.miniProgramID, path: YqbApp.miniProgramPath(id: YqbApp.getServiceData()!.id)));
                }, child: Image.asset("images/chat_we.png", width: 125)),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
